#ifndef __REF_OBJ_H__
#define __REF_OBJ_H__

template<typename _Ty>
class RefObj
{
	template<typename _Ty>
	class ref_obj : public _Ty
	{
	public:
		ref_obj(void)
			: m_ref(1)
		{
		}

		~ref_obj(void)
		{
		}

		void addref()
		{
			m_ref++;
		}

		void release()
		{
			m_ref--;
			if (m_ref == 0)
			{
				delete this;
			}
		}

	private:
		unsigned int m_ref;
	};
public:
	RefObj()
	{
		Init();
	}

	RefObj(const RefObj& r)
	{
		m_p = r.m_p;
		if (m_p)
		{
			m_p->addref();
		}
	}

	~RefObj()
	{
		if (m_p)
		{
			m_p->release();
			m_p = NULL;
		}
	}

	operator _Ty& () const
	{
		return *m_p;
	}

	_Ty* operator& () const
	{
		return m_p;
	}

	_Ty* operator-> () const
	{
		return m_p;
	}

	RefObj& operator = (const _Ty& v)
	{
		*(_Ty*)m_p = v;
		return *this;
	}

	RefObj& operator = (const RefObj& r)
	{
		if (m_p != r.m_p)
		{
			if (m_p)
			{
				m_p->release();
			}

			m_p = r.m_p;

			if (m_p)
			{
				m_p->addref();
			}
		}

		return *this;
	}

private:
	ref_obj<_Ty> * m_p;

	void Init()
	{
		m_p = new ref_obj<_Ty>;
	}
};

#endif